// 全局钱包状态管理器
import web3WalletService from './web3.js';

class WalletManager {
  constructor() {
    this.isInitialized = false;
    this.currentAddress = null;
    this.isConnected = false;
    this.addressChangeCallbacks = [];
    this.loginCallbacks = [];
  }

  // 初始化钱包管理器
  async init(i18n) {
    if (this.isInitialized) return;
    
    // 设置Web3服务的国际化实例
    web3WalletService.setI18n(i18n);
    
    // 注册地址变化监听
    web3WalletService.onAddressChange(this.handleAddressChange.bind(this));
    
    this.isInitialized = true;
    console.log('钱包管理器已初始化');
  }

  // 处理地址变化
  handleAddressChange(oldAccount, newAccount) {
    console.log('🔗 钱包管理器收到地址变化事件:', { oldAccount, newAccount });
    
    this.currentAddress = newAccount;
    this.isConnected = !!newAccount;
    
    console.log('🔗 注册的地址变化回调数量:', this.addressChangeCallbacks.length);
    
    // 触发地址变化回调
    this.addressChangeCallbacks.forEach((callback, index) => {
      try {
        console.log(`🔗 执行地址变化回调 ${index}`);
        callback(oldAccount, newAccount);
      } catch (error) {
        console.error('地址变化回调执行失败:', error);
      }
    });
    
    // 只在真正的新连接时触发登录回调（避免重复触发）
    if (!oldAccount && newAccount) {
      console.log('🔄 新连接，触发自动签名登录流程');
      console.log('🔄 注册的登录回调数量:', this.loginCallbacks.length);
      this.triggerLoginCallbacks(newAccount);
    } else {
      console.log('🔄 跳过登录回调触发（非新连接）');
    }
  }

  // 注册地址变化回调
  onAddressChange(callback) {
    if (typeof callback === 'function') {
      this.addressChangeCallbacks.push(callback);
    }
  }

  // 移除地址变化回调
  offAddressChange(callback) {
    const index = this.addressChangeCallbacks.indexOf(callback);
    if (index > -1) {
      this.addressChangeCallbacks.splice(index, 1);
    }
  }

  // 注册登录回调
  onLogin(callback) {
    if (typeof callback === 'function') {
      this.loginCallbacks.push(callback);
	 
    }
  }

  // 移除登录回调
  offLogin(callback) {
    const index = this.loginCallbacks.indexOf(callback);
    if (index > -1) {
      this.loginCallbacks.splice(index, 1);
    }
  }

  // 触发登录回调
  triggerLoginCallbacks(address) {
    console.log('触发登录回调，地址:', address);
    this.loginCallbacks.forEach(callback => {
      try {
        callback(address);
		 // uni.$emit('loginFailed', '邀请码错误');
      } catch (error) {
        console.error('登录回调执行失败:', error);
      }
    });
  }

  // 获取当前地址
  getCurrentAddress() {
    return this.currentAddress;
  }

  // 检查是否已连接
  isWalletConnected() {
    return this.isConnected;
  }

  // 强制检查钱包地址
  async forceCheckWalletAddress() {
    return await web3WalletService.forceCheckWalletAddress();
  }

  // 连接钱包
  async connectWallet() {
    return await web3WalletService.connectBSC();
  }

  // 断开钱包连接
  disconnectWallet() {
    web3WalletService.disconnect();
  }

  // 自动连接钱包
  async autoConnect() {
    return await web3WalletService.autoConnect();
  }
}

// 创建单例实例
const walletManager = new WalletManager();

export default walletManager;
